package com.vecspace.scheduler;

import java.util.ArrayList;
import java.util.List;

import org.quartz.SchedulerException;

import com.vecspace.exception.HException;
import com.vecspace.scheduler.job.AbstractJob;
import com.vecspace.scheduler.job.GroupJob;



/**
 *  
 */
public class JobScheduler {
	private List<AbstractJob> jobs = new ArrayList<>();
	private AbstractJob job;
 
	/**在每天的指定时间执行 2:30*/
	private String atTime;
	
	/**每间隔一段时间执行（秒）*/
	private int intervalSeconds;
	
	/**执行时间由cron表达式定义*/
	private String cronExpression;
	
	
	private boolean force;
	
	public List<AbstractJob> getJobs() {
		return jobs;
	}
	public void setJobs(List<AbstractJob> jobs) {
		this.jobs = jobs;
	}
	
	public AbstractJob getJob() {
		return job;
	}
	public void setJob(AbstractJob job) {
		this.job = job;
	}

	public String getAtTime() {
		return atTime;
	}
	public void setAtTime(String atTime) {
		this.atTime = atTime;
	}
	
	public int getIntervalSeconds() {
		return intervalSeconds;
	}
	public void setIntervalSeconds(int intervalSeconds) {
		this.intervalSeconds = intervalSeconds;
	}
	
	public String getCronExpression() {
		return cronExpression;
	}
	public void setCronExpression(String cronExpression) {
		this.cronExpression = cronExpression;
	}
	
	
	public boolean isForce() {
		return force;
	}
	public void setForce(boolean force) {
		this.force = force;
	}
	
	public void start() throws HException, SchedulerException{
		if(jobs == null) {
			jobs = new ArrayList<>();
		}
		if(job != null) {
			jobs.add(job);
		}
		
		if(jobs.size() == 0)return;
		
		AbstractJob groupJob = new GroupJob(jobs);
		if(atTime != null && atTime.trim().length()>0){
			atTime = atTime.trim();
			String[] timeArr = atTime.split(":|：");
			if(timeArr.length == 2){
				int hour = Integer.parseInt(timeArr[0]);
				int minute = Integer.parseInt(timeArr[1]);
				HScheduler.startExecuteJobEveryday(groupJob, hour, minute);
			}else{
				throw new HException("atTime属性定义不正确:"+atTime+","+groupJob.getClass().getName());
			}			
		}else if(intervalSeconds > 0){
			HScheduler.startExecuteJobInteval(groupJob, intervalSeconds, force);
		}else if(cronExpression != null && cronExpression.trim().length()>0){
			throw new HException("没有实现此方式：cronExpression");
		}else{
			throw new HException("没有定义执行时间atTime, intervalSeconds或者cronExpression:"+groupJob.getClass().getName());
		}
	}
}
